import jwt from 'jsonwebtoken';
import type { User } from '@prisma/client';

const JWT_SECRET: string = process.env.JWT_SECRET || 'your-secret-key-change-in-production';
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '7d';

export interface JWTPayload {
  userId: string;
  username: string;
  role: number;
  iat?: number;
  exp?: number;
}

// 生成JWT token
export function generateToken(user: User): string {
  const payload: JWTPayload = {
    userId: user.id,
    username: user.username,
    role: user.role,
  };

  // 确保 expiresIn 是有效的类型
  const expiresIn = JWT_EXPIRES_IN || '7d';

  return jwt.sign(payload, JWT_SECRET, {
    expiresIn: expiresIn as '7d' | '1d' | '30d' | number,
  });
}

// 验证JWT token
export function verifyToken(token: string): JWTPayload | null {
  try {
    const decoded = jwt.verify(token, JWT_SECRET) as JWTPayload;
    return decoded;
  } catch (error) {
    console.error('JWT验证失败:', error);
    return null;
  }
}

// 从请求头中提取token
export function extractTokenFromHeader(authHeader: string | null): string | null {
  if (authHeader && authHeader.startsWith('Bearer ')) {
    return authHeader.substring(7);
  }
  return null;
}